package com.lhn.netty.netty_demo.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author lhn
 * @date 2025/06/11 19:32
 * @since 1.0.0
 **/
public class MyServerHandler extends SimpleChannelInboundHandler <ByteBuf> {
    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        // 将byteBuf 转换成字符串
        String string = new String(bytes, "utf-8");
        System.out.println("服务端接收到消息 :   " + string);

        System.out.println("服务端接收到的消息长度 : " + byteBuf.readableBytes());

        channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer(UUID.randomUUID().toString(), StandardCharsets.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}